package gui;

import gui.MainFrame;

import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Point;
import java.awt.Shape;
import java.awt.Toolkit;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.font.TextAttribute;
import java.awt.geom.RoundRectangle2D;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;
import java.util.Hashtable;
import javax.swing.*;
import javax.swing.border.EtchedBorder;

import Projektarbete.ContactTabListFiller;

/**
 * @author Calle, Jerry, Tim
 */
public class LoginScreen extends JFrame implements KeyListener {

	private static final long serialVersionUID = 1L;

	private ImagePanel mainPanel;
	private JLabel logoLabel;
	private JPanel loginPanel;
	private JLabel usernameLabel;
	private JLabel passwordLabel;
	private JLabel errorMessageLabel;
	private JLabel rememberLabel;
	private JLabel memberText;
	private JLabel registerText;
	private JLabel forgotButton;
	private JTextField usernameInput;
	private JPasswordField passInput;
	private JButton loginButton;
	private JCheckBox rememberCheckBox;
	private JLabel exitButton;
	private Point point;
	private MainFrame mf;
	private Hashtable<TextAttribute, Object> map;
	private Font mainFont;
	private Font forgotFont;
	private LoginScreen thisFrame = this;

	public LoginScreen() {
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (UnsupportedLookAndFeelException e) {
			e.printStackTrace();
		}
		initComponents();
	}

	private void initComponents() {

		setUndecorated(true);
		mainPanel = new ImagePanel("src/loginBackground.png");
		logoLabel = new JLabel();
		loginPanel = new JPanel();
		usernameLabel = new JLabel("Username");
		passwordLabel = new JLabel("Password");
		errorMessageLabel = new JLabel();
		memberText = new JLabel("Not a member?");
		registerText = new JLabel("Register!");
		rememberLabel = new JLabel("Remember me");
		forgotButton = new JLabel("Forgot username/password");
		loginButton = new JButton("Login");
		usernameInput = new JTextField();
		passInput = new JPasswordField();
		rememberCheckBox = new JCheckBox();
		exitButton = new JLabel();
		map = new Hashtable<TextAttribute, Object>();
		map.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON);
		point = new Point();

		rememberCheckBox.setOpaque(false);
		loginButton.setOpaque(false);
		Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
		int X = (screen.width / 2) - 200;
		int Y = (screen.height / 2) - 225;
		setBounds(X, Y, WIDTH, HEIGHT);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setResizable(false);
		setIconImage(new ImageIcon("src/icon.png").getImage());

		logoLabel.setBorder(BorderFactory
				.createEtchedBorder(EtchedBorder.LOWERED));
		logoLabel.setIcon(new ImageIcon("src/HorizonSmall.png"));

		loginPanel.setBackground(new Color(5, 100, 98));
		loginPanel.setBorder(BorderFactory.createEtchedBorder());
		loginPanel.setPreferredSize(new java.awt.Dimension(300, 200));

		mainFont = new Font("Aliquam", Font.PLAIN, 14);
		forgotFont = new Font("Aliquam", Font.PLAIN, 14);
		usernameLabel.setFont(new Font("Aliquam", 0, 18));
		passwordLabel.setFont(new Font("Aliquam", 0, 18));
		rememberLabel.setFont(new Font("Aliquam", 0, 12));
		memberText.setFont(mainFont);
		registerText.setFont(mainFont);
		forgotButton.setFont(forgotFont);
		loginButton.setFont(new Font("Aliquam", 1, 14));

		usernameInput.addKeyListener(this);
		passInput.addKeyListener(this);
		rememberCheckBox.addKeyListener(this);

		// cookies
		String namePassArray[] = { "", "" };

		BufferedReader br = null;
		try {
			br = new BufferedReader(new FileReader("cookies.txt"));
			String word;
			int i = 0;
			while ((word = br.readLine()) != null) {
				namePassArray[i] = word;
				i++;
			}
			if(namePassArray[0].length() > 0){
				rememberCheckBox.doClick();
			}
		} catch (IOException e) {
		}
		exitButton.setIcon(new javax.swing.ImageIcon("src/quit.png")); // NOI18N
		exitButton.addMouseListener(new java.awt.event.MouseAdapter() {
			public void mouseClicked(java.awt.event.MouseEvent evt) {
				shutDown(evt);
			}

			private void shutDown(MouseEvent evt) {
				thisFrame.dispose();
			}

			public void mouseEntered(java.awt.event.MouseEvent evt) {
				mouseOver(evt);
			}

			private void mouseOver(MouseEvent evt) {
				exitButton
						.setIcon(new javax.swing.ImageIcon("src/quitOver.png"));

			}

			public void mouseExited(java.awt.event.MouseEvent evt) {
				mouseNotOver(evt);
			}

			private void mouseNotOver(MouseEvent evt) {
				exitButton.setIcon(new javax.swing.ImageIcon("src/quit.png"));

			}

			public void mousePressed(java.awt.event.MouseEvent evt) {
				pressQuit(evt);
			}

			private void pressQuit(MouseEvent evt) {
				exitButton.setIcon(new javax.swing.ImageIcon(
						"src/quitPressed.png"));

			}

			public void mouseReleased(java.awt.event.MouseEvent evt) {
				mouseOver(evt);
			}

		});

		usernameInput.setText(namePassArray[0]);
		passInput.setText(namePassArray[1]);

		errorMessageLabel.setForeground(new Color(255, 0, 0));

		

		registerText.addMouseListener(new java.awt.event.MouseAdapter() {
			public void mouseClicked(java.awt.event.MouseEvent evt) {
				openRegister(evt);
			}

			private void openRegister(java.awt.event.MouseEvent evt) {
				new RegisterDialog(thisFrame, true);
			}

			public void mouseEntered(java.awt.event.MouseEvent evt) {
				underline(evt);
			}

			@SuppressWarnings("deprecation")
			private void underline(java.awt.event.MouseEvent evt) {
				mainFont = mainFont.deriveFont(map);
				registerText.setFont(mainFont);
				setCursor(Cursor.HAND_CURSOR);
			}

			public void mouseExited(java.awt.event.MouseEvent evt) {
				noUnderline(evt);
			}

			@SuppressWarnings("deprecation")
			private void noUnderline(java.awt.event.MouseEvent evt) {
				registerText.setFont(new Font("Aliquam", Font.PLAIN, 14));
				setCursor(Cursor.DEFAULT_CURSOR);
			}

		});

		forgotButton.addMouseListener(new java.awt.event.MouseAdapter() {
			public void mouseClicked(java.awt.event.MouseEvent evt) {
				openForgot(evt);
			}

			private void openForgot(MouseEvent evt) {
				try {
					java.net.URI uri = new java.net.URI("http://www.kth.se");
					java.awt.Desktop.getDesktop().browse(uri);
				} catch (Exception g) {
					System.out.println(g.toString());
				}

			}

			public void mouseEntered(java.awt.event.MouseEvent evt) {
				underlineForgot(evt);
			}

			@SuppressWarnings("deprecation")
			private void underlineForgot(MouseEvent evt) {
				forgotFont = forgotFont.deriveFont(map);
				forgotButton.setFont(forgotFont);
				setCursor(Cursor.HAND_CURSOR);
			}

			public void mouseExited(java.awt.event.MouseEvent evt) {
				noUnderlineForgot(evt);
			}

			@SuppressWarnings("deprecation")
			private void noUnderlineForgot(MouseEvent evt) {
				forgotButton.setFont(new Font("Aliquam", Font.PLAIN, 14));
				setCursor(Cursor.DEFAULT_CURSOR);
			}
		});

		javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addComponent(forgotButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 77, Short.MAX_VALUE)
                        .addComponent(rememberLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(rememberCheckBox)
                        .addGap(31, 31, 31))
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(mainPanelLayout.createSequentialGroup()
                                .addComponent(memberText)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(registerText, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addComponent(loginButton)
                                .addGroup(mainPanelLayout.createSequentialGroup()
                                    .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(usernameLabel)
                                        .addComponent(passwordLabel))
                                    .addGap(18, 18, 18)
                                    .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                        .addComponent(usernameInput, javax.swing.GroupLayout.DEFAULT_SIZE, 231, Short.MAX_VALUE)
                                        .addComponent(passInput)))))
                        .addGap(0, 0, Short.MAX_VALUE))))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(exitButton)
                .addGap(21, 21, 21))
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup()
                .addComponent(exitButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 209, Short.MAX_VALUE)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(usernameInput, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(usernameLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(passwordLabel)
                    .addComponent(passInput, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(forgotButton)
                        .addComponent(rememberLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(rememberCheckBox))
                .addGap(18, 18, 18)
                .addComponent(loginButton)
                .addGap(21, 21, 21)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(memberText)
                    .addComponent(registerText))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(mainPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 376, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(mainPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 413, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
        );



		loginButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				login();
			}
		});
		addMouseListener(new MouseAdapter() {
			public void mousePressed(MouseEvent e) {
				point.x = e.getX();
				point.y = e.getY();

			}
		});
		addMouseMotionListener(new MouseMotionAdapter() {
			public void mouseDragged(MouseEvent e) {
				Point p = getLocation();

				if (point.y <= 222) {
					setLocation(p.x + e.getX() - point.x, p.y + e.getY()
							- point.y);
				}
			}

		});
		pack();
		java.awt.Window wind = new java.awt.Window(thisFrame);
		Shape shape = null;
		shape = new RoundRectangle2D.Double(0, 0, thisFrame.getWidth(),
				thisFrame.getHeight(), 25, 25);
		//wind.getOwner().setShape(shape);
		setVisible(true);
	}

	public void login() {
		new ContactTabListFiller().loginUser(usernameInput, passInput, mf,
				rememberCheckBox, thisFrame);
	}

	@Override
	public void keyPressed(KeyEvent arg0) {
	}

	@Override
	public void keyReleased(KeyEvent arg0) {
		if (arg0.getKeyCode() == 10) {
			login();
		}
	}

	@Override
	public void keyTyped(KeyEvent arg0) {
	}
}
